//
//  MKOauthViewController.swift
//  MKWeiBo2017
//
//  Created by nicolas on 2017/5/13.
//  Copyright © 2017年 nicolas. All rights reserved.
//

import UIKit
import SVProgressHUD

class MKOauthViewController: UIViewController {
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = GlobalBKGColor
        
        //设置导航栏
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.plain, target: self, action: #selector(autoFill))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.plain, target: self, action: #selector(close))
        navigationItem.title = "登录"
        
        let urlString = oauthURLString + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri

        let url = NSURL(string: urlString)
        
        let request =  URLRequest(url: url as! URL)
        
        webView.loadRequest(request)
    
        SVProgressHUD.show(withStatus: "正在加载...")
    }
    
   @objc private func autoFill () {
    
        let jsString = "document.getElementById('userId').value='1842158575@qq.com';document.getElementById('passwd').value='Zlei0809';"
    
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    
    func close () {
       SVProgressHUD.dismiss()
       dismiss(animated: true, completion: nil)
    }
    //懒加载
    private lazy var webView: UIWebView = UIWebView()
   
}

extension MKOauthViewController: UIWebViewDelegate {
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let url = request.url!
       
        if !url.absoluteString.hasPrefix(redirect_uri) {
            // 只要不是授权回调地址,是新浪的界面,就让他去加载
            return true
        } else {
            // 是授权回调地址,点击的是取消或授权,不让他去加载,我们自己来做一些事情
            // URL的query: ?后面的东西
            let query = url.query!
            //            CZPrint(items: "query: \(query)")
            let codeString = "code="
            if query.hasPrefix(codeString) {
                // 如果query 是以 code=开头表示点击的授权按钮
                // 从query中截取code的值,substringFromIndex从指定位置截取到最后
                let code = (query as NSString).substring(from: codeString.characters.count)
                MKPrint(items: "---------code:\(code)")

                /// 加载AccessToken,字典转模型,模型保存到沙盒
                            MKUserAccountViewModel.sharedInstance.loadAccessToken(code: code, callback: { (error) in
                               
                                if error != nil {
                                    
                                                            SVProgressHUD.showError(withStatus: "您的网络不给力...")
                                    
                                    // 延迟一秒关闭
                                    let time: TimeInterval = 1.0
                                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time, execute: { 
                                        self.close()
                                    })
                                    
                                } else {
                                    // 没有错误
                                    self.close()
                                    // 跳转到CZWelcomeViewCotroller
                                    // 调用AppDelegate的switchRootViewContriller
                                    let appDelegate = (UIApplication.shared.delegate as! AppDelegate)
                                    appDelegate.switchRootViewController(controller: MKWelcomeViewController())
                                }
                            })
                
            } else{
                // 点击的是取消按钮
                close()
            }
            
            return false
        }
    }

}
